const multiparty = require("multiparty"),
  SparkMD5 = require("spark-md5"),
  fs = require("fs");
const fileurl = require("@/url");

const uploadDir = fileurl + "\\public\\uploaded";
const multiparty_upload = function multiparty_upload(req, auto) {
  // auto用于设置插件的自动上传
  typeof auto !== "boolean" ? (auto = false) : null;
  let config = {
    maxFieldsSize: 200 * 1024 * 1024,
  };
  if (auto) config.uploadDir = uploadDir;
  return new Promise(async (resolve, reject) => {
    new multiparty.Form(config).parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
        return;
      }
      resolve({
        fields,
        files,
      });
    });
  });
};

async function UploadFile(req) {
  try {
    let { files } = await multiparty_upload(req, true);
    let file = (files.file && files.file[0]) || {};
    return file.path.split("uploaded\\")[1];
  } catch (err) {
    return {
      err,
    };
  }
}

module.exports = {
  UploadFile,
};
